package com.boot.project.wechat.applet.web;



import com.boot.project.domain.OrderDo;
import com.boot.project.sdk.HttpKit;
import com.boot.project.sdk.PaymentKit;
import com.boot.project.service.OrderService;
import com.boot.project.wechat.base.BjddController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/****************************************************
 *
 *   小程序回调控制器
 *
 * @author HW
 * @version 1.0
 **************************************************/
@RestController
@RequestMapping("m/pay/")
public class PayApi extends BjddController {
    @Autowired
    private OrderService orderService;
    /**
     * 成功的标识
     */
    private final static String SUCCESS="SUCCESS";

    /**
     * 返回状态码的变量名
     *
     */
    private final static String RETURN_CODE="RETURN_CODE";


    /**
     * 功能描述: <小程序回调>
     * @return:
     * @auther: HW
     **/
    @RequestMapping("/wxProPayNotify/anon")
    public void wxProPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //logger.info("进入微信小程序支付回调");
        String xmlMsg = HttpKit.readData(request);
        //logger.info("微信小程序通知信息"+xmlMsg);
        Map<String, String> resultMap = PaymentKit.xmlToMap(xmlMsg);
        if(resultMap.get(RETURN_CODE).equals(SUCCESS)){
            String orderNo = resultMap.get("out_trade_no");
            //logger.info("微信小程序支付成功,订单号{}",orderNo);
            /**
             *  通过订单号 修改数据库中的记录
             */
            System.out.println("进来了"+"<<<<<<<<<<<<<<<<<<<<<<<<<<<");
            OrderDo orderDo = new OrderDo();
            orderDo.setStatus(1);
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
            orderDo.setPayTime(new Date());
            orderService.update(orderDo);
        }
        String result =  "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        try {
            response.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
